package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.common.utils.RegexUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;


/**
 * @author syf
 * @version 1.0
 * @date 2019/08/11 21:35
 * @Description TODO:
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder; //PasswordConfig中的方法

    //标识
    private static final String MSG_CHECK_CODE_PRE="MSG_CHECK_CODE_PRE";
    //数据验证
    public Boolean checkUserData(String data, Integer type) {

        User user=new User();
        //细粒度：判读等级
        //data:要验证的数据 ；type:要校验的数据类型：1，用户名；2，手机
        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                //无效的请求参数
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        int count = userMapper.selectCount(user);
        //如果没有查询到为true
        return count==0;
    }

    //发送短信
    public void sendCode(String phone) {
        //验证手机号格式
        if (!RegexUtils.isPhone(phone)){
            //无效的手机号码
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        //生成验证码
        String code = RandomStringUtils.randomNumeric(6);//6位数
        //保存验证码到redis    保存30分钟
        redisTemplate.opsForValue().set( MSG_CHECK_CODE_PRE + phone, code, 6, TimeUnit.HOURS);

        // 封装发送RabbitMQ消息到
        Map<String,String>map=new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        //向指定队列中发送mq消息
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, map);
    }

    //用户注册
    public void register(User user,String code, String confirmPassword) {
        try {
            //验证验证码是否正确
            String redisCode=redisTemplate.opsForValue().get(MSG_CHECK_CODE_PRE+user.getPhone());
            if (!StringUtils.equals(code,redisCode)){
                throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
            }
            //验证两个密码是否一致
            if (!StringUtils.equals(confirmPassword,user.getPassword())){
                throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
            }
            //对密码进行加密
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            //保存数据
            userMapper.insertSelective(user);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

    }
    //根据用户名和密码查询用户
    public UserDTO findByUsernameAndPassword(String username, String password) {
        try {
            //先查询用户名是否正确
            User record = new User();
            record.setUsername(username);
            User userInfo = userMapper.selectOne(record);
            //再查询密码是否正确
            boolean matches = bCryptPasswordEncoder.matches(password, userInfo.getPassword());
            if (matches) {
                //把user转为DTO
                return BeanHelper.copyProperties(userInfo, UserDTO.class);
            }
            //无效的用户名和密码
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);

        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }
}
